package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.*;
import cn.tedu.csmall.commons.vo.PageData;
import cn.tedu.csmall.product.pojo.entity.Sku;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.entity.SpuDetail;
import cn.tedu.csmall.product.pojo.param.SpuAddNewParam;
import cn.tedu.csmall.product.pojo.vo.*;
import cn.tedu.csmall.product.service.ISpuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author Administrator
 * @description 针对表【pms_spu(SPU（Standard Product Unit）)】的数据库操作Service实现
 * @createDate 2023-06-15 14:23:09
 */
@Service
@Slf4j
public class SpuServiceImpl implements ISpuService {


    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private AttributeTemplateMapper attributeTemplateMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SkuMapper skuMapper;


    @Override
    public void addNew(SpuAddNewParam spuAddNewParam) {
        log.info("开始处理[添加SPU]的业务");
        log.debug("参数:{}", spuAddNewParam);

        //检查相册ID是否存在
        Long albumID = spuAddNewParam.getAlbumId();
        AlbumStandardVO albumStandardVO = albumMapper.getStandardById(albumID);
        if (albumStandardVO == null) {
            log.info("根据相册ID查询，结果为null，抛出异常");
            String message = "新增Spu失败，相册数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //检查属性模版ID是否存在
        Long attributeTemplateID = spuAddNewParam.getAttributeTemplateId();
        AttributeTemplateStandardVO attributeTemplateStandardVO = attributeTemplateMapper.getStandardById(attributeTemplateID);
        if (attributeTemplateStandardVO == null) {
            log.info("根据属性模版ID查询，结果为null，抛出异常");
            String message = "新增Spu失败，属性模版数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        
        //检查品牌ID是否存在
        Long brandId = spuAddNewParam.getBrandId();
        BrandStandardVO brandStandardVO = brandMapper.getStandardById(brandId);
        if (brandStandardVO == null) {
            log.info("根据品牌ID查询，结果为null，抛出异常");
            String message = "新增Spu失败，品牌数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (brandStandardVO.getEnable() == 0 ){
            log.info("根据类别ID查询，品牌已经被禁用，抛出异常");
            String message = "新增Spu失败，品牌已被禁用！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }


        //检查类别ID是否存在
        Long categoryID = spuAddNewParam.getCategoryId();
        CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(categoryID);
        if (categoryStandardVO == null) {
            log.info("根据类别ID查询，结果为null，抛出异常");
            String message = "新增Spu失败，类别数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (categoryStandardVO.getEnable() == 0 ){
            log.info("根据类别ID查询，类别已经被禁用，抛出异常");
            String message = "新增Spu失败，类别已被禁用！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        if (categoryStandardVO.getIsParent() == 1 ){
            log.info("根据类别ID查询，类别是父级，抛出异常");
            String message = "新增Spu失败，类别是父级！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        long spuId = new Random().nextInt(1000000);
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuAddNewParam,spu);
        spu.setId(spuId)
                .setBrandName(brandStandardVO.getName())
                .setCategoryName(categoryStandardVO.getName())
                .setSales(0)
                .setCommentCount(0)
                .setPositiveCommentCount(0)
                .setIsDeleted(0)
                .setIsPublished(0)
                .setIsNewArrival(0)
                .setIsRecommend(0)
                .setIsChecked(0);

        log.debug("新增Spu数据,spu={}",spu);
        int rows = spuMapper.insert(spu);
        if (rows !=1){
            String message = "添加SPU失败！服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.info("添加SPU成功！");


        SpuDetail spuDetail= new SpuDetail();
        spuDetail.setSpuId(spuId)
                .setDetail(spuAddNewParam.getDetail());
        rows = spuDetailMapper.insert(spuDetail);
        if (rows !=1){
            String message = "添加SPU失败！服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.info("添加SPU成功！");






    }

    @Override
    public void deleteById(Long id) {
        log.info("开始处理【删除Spu】的业务");
        log.debug("传入参数,id={}", id);

        //检查SpuID检查Spu是否存在数据，如果不存在，则抛出异常
        SpuStandardVO standardById = spuMapper.getStandardById(id);
        log.info("根据Spuid检索数据库结果,standardById={}", standardById);
        if(standardById == null){
            String message = "删除Spu失败，Spu数据不存在！";
            log.info("根据Spuid检索数据量为0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //根据SpuID检查Sku表是否存在数据，如果存在，则抛出异常
        QueryWrapper<Sku> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("spu_id", id);
        Integer count = skuMapper.selectCount(queryWrapper3);
        log.info("根据Spuid检索Sku数据库结果,count={}", count);
        if(count > 0){
            String message = "删除Spu失败，Sku表内有关联数据！";
            log.info("根据SpuId检索属性数据量>0，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        int rows = spuMapper.deleteById(id);
        if(rows != 1){
            String message = "删除Spu失败，服务器忙，请稍后再试！";
            log.info("数据返回行数不满足预估行数，预估={}, 实际={}, 抛出自定异常...", 1, rows);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.info("删除Spu结果,rows={}", rows);
    }

    @Override
    public SpuStandardVO getStandardById(Long id) {
        log.info("开始处理【根据ID查询Spu】的业务");
        log.debug("参数,id={}", id);
        SpuStandardVO standardById = spuMapper.getStandardById(id);

        //根据SpuID检查Spu是否存在数据，如果不存在，则抛出异常
        if(standardById==null){
            log.info("根据SpuId查询详情，结果为null，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "查询Spu详情失败，Spu数据不存在");
        }

        log.info("查询出数据,standardById");
        return standardById;
    }

    @Override
    public SpuFullInfoVO getFullInfoById(Long id) {
        log.info("开始处理【根据ID查询Spu详情】的业务");
        log.debug("参数,id={}", id);
        SpuFullInfoVO fullInfoById = spuMapper.getFullInfoById(id);

        //根据SpuID检查Spu是否存在数据，如果不存在，则抛出异常
        if(fullInfoById==null){
            log.info("根据SpuId查询详情，结果为null，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "查询Spu详情失败，Spu数据不存在");
        }
        log.info("查询出数据,standardById");
        return fullInfoById;
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum, Integer pageSize) {
        log.info("开始处理【查询-Spu-分页】的业务");
        log.debug("参数, pageNum={}, pageSize={}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<SpuListItemVO> list = spuMapper.list();
        PageInfo<SpuListItemVO> pageInfo = new PageInfo<>(list);
        PageData<SpuListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询结果：pageData={}", pageData);
        return pageData;
    }
}




